import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider, Icon, Badge, PageHeader } from 'antd';
import '@/assets/css/settings';
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import * as APIService from '../../../axios/api_px'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareNum, compareString } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
import DetailSearchForm from './DetailSearchForm';
import EditTable from '../../../components/EditRowTable';
import { withRouter } from 'react-router';
const CreateButton = withPermission(Button, 'create')

class SelfCheckingManageDetail extends Component {
    state = {
        dataSource: [],
        visible: false,
        searchItem: {},
        searchItemFather: {},
        formData: {},
        pageSize: 10,
        pageNum: 1,
        total: 0,
        clickSaveFlag: false,   // true 禁用  false 启用
        columns: [
            {
                title: '序号',
                dataIndex: 'dataIndex',
                align: 'center',
                width: 50,
                render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
            },
            {
                title: '检验项目',
                dataIndex: 'checkItem',
                width: 400,
                editable: true,
                required: true,
                sorter: (a, b) => compareString(a.checkItem, b.checkItem)
            },
            {
                title: '检查情况',
                width: 200,
                // allowEllipsis: true,
                dataIndex: 'checkSituation',
                sorter: (a, b) => compareString(a.checkSituation, b.checkSituation)
            },
            {
                title: '纠正措施',
                width: 200,
                // allowEllipsis: true,
                dataIndex: 'correctiveAction',
                sorter: (a, b) => compareString(a.correctiveAction, b.correctiveAction)
            },
            {
                title: '备注',
                width: 100,
                // allowEllipsis: true,
                dataIndex: 'remark',
                sorter: (a, b) => compareString(a.remark, b.remark)
            },
            {
                title: '创建人',
                width: 100,
                // allowEllipsis: true,
                dataIndex: 'creater',
                sorter: (a, b) => compareString(a.creater, b.creater)
            },
            {
                title: '创建时间',
                width: 150,
                // allowEllipsis: true,
                dataIndex: 'createTime',
                sorter: (a, b) => compareDate(a.createTime, b.createTime)
            },
            {
                title: '操作',
                dataIndex: 'opts',
                width: 100,
                render: (text, record) => {
                    const { editingKey, clickSaveFlag } = this.state;
                    const editable = record.id === editingKey;
                    return editable ? (
                        <span>
                            <a
                                disabled={clickSaveFlag}
                                onClick={() => {
                                    this.handleSave(record)
                                }}
                                style={{ marginRight: 8 }}
                            >
                                保存
                            </a>
                            <Divider type='vertical' />
                            <a onClick={() => this.cancel()}>取消</a>
                        </span>
                    ) : (
                        <span>
                            <a disabled={editingKey !== ''} onClick={() => this.edit(record.id)}>
                                编辑
                            </a>
                            <Divider type='vertical' />
                            <a disabled={editingKey !== ''} onClick={() => this.handleDelete(0, record)}>
                                删除
                            </a>
                        </span>
                    );
                }
            },
            { dataIndex: '' }
        ],
        editingKey: '',
        selectedRows: [],
        selectedRowKeys: [],
        downloadLoading: false,
        drawerVisible: false,  // 新增
    };
    componentDidMount() {
        this.setState({
            formData: this.props.location?.data?.formData ? this.props.location.data.formData : JSON.parse(localStorage.getItem('SelfCheckingManage_detailsList')),
            searchItemFather: this.props.location?.data?.searchItemFather ? this.props.location.data.searchItemFather : JSON.parse(localStorage.getItem('SelfCheckingManage_searchItem')),
            searchItem: this.props.location?.data?.searchItem ? this.props.location.data.searchItem : JSON.parse(localStorage.getItem('SelfCheckingManage_Report')) ? JSON.parse(localStorage.getItem('SelfCheckingManage_Report')).searchItem : {}
        }, this.fetch)
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    //初始化加载数据
    fetch = (pageNum = 1, pageSize = 100) => {
        this.setState({ loading: true })
        const { searchItem, formData } = this.state
        searchItem.pageNum = pageNum
        searchItem.pageSize = pageSize
        searchItem.masterId = formData?.id

        APIService.querySelfCheckDetail(searchItem).then(res => {
            this.setState({ loading: false })
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg)
                return
            }
            this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize, selectedRowKeys: [], selectedRows: [], row: [], editingKey: '' })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
    }

    // 点击新增按钮
    handleAdd = () => {
        const { dataSource } = this.state;

        const newData = {
            id: '自检表',
            checkItem: ``,
        };
        this.setState({
            dataSource: [newData, ...dataSource],
            editingKey: '自检表',
            newData,
            isAdd: true
        });
    }
    // 点击编辑按钮
    edit = (id) => { this.setState({ editingKey: id }); }
    // 点击取消按钮
    cancel = () => {
        const { newData, isAdd } = this.state
        if (isAdd) {
            this.handleDelete(0, newData)
        }
        this.setState({ editingKey: '', clickSaveFlag: false });
    };

    // 保存
    handleSave = (row) => {
        // console.log(row, 'row')
        this.setState({ clickSaveFlag: true })
        this.editTable1.validateFields((err, value) => {
            if (err) {
                this.setState({ clickSaveFlag: false })
                return
            }
            this.newOrCompile({ ...row, ...value })
        })
    };
    //新增/编辑接口
    newOrCompile = (value) => {
        const { formData } = this.state
        if (value.id == '自检表') {
            delete value.id
        }
        value.masterId = formData.id
        // console.log(value, 'newOrCompile')
        APIService.alterSelfCheckDetail(value).then((item) => {
            this.setState({ clickSaveFlag: false })
            if (item.data.code === 200) {
                openSuccessModal(item.data.msg)
                this.fetch()
                this.setState({ isAdd: false })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 点击删除按钮
    handleDelete = (type, record = {}) => {
        let arr = [], data = ''
        // type   0 单个删除   1 批量删除
        if (type == 0) {
            console.log(record, 'record')
            const then = this
            if (record.id == "自检表") {
                const dataSource = [...this.state.dataSource];
                this.setState({ isAdd: false })
                this.setState({ dataSource: dataSource.filter(item => item.id !== record.id) });
                return
            } else {
                // arr.push(record.id)
                data += 'idList=' + record.id + '&'
            }
        } else if (type == 1) {
            const { selectedRows } = this.state
            if (!selectedRows || !selectedRows.length) {
                openModalMessage('warning', '请选择要删除的数据！');
                return;
            }
            selectedRows.map(item => {
                // arr.push(item.id)
                data += 'idList=' + item.id + '&'
            })
        }

        // let data = {
        //     "id": arr,
        //     "userId": localStorage.getItem('userId')
        // }
        const that = this;
        Modal.confirm({
            title: '提示',
            content: '确认要删除所选数据吗？',
            onOk: async () => {
                await APIService.deleteSelfCheckDetail(data).then(res => {
                    if (res.data.code !== 200) {
                        openModalMessage('warning', res.data.msg);
                        return;
                    }
                    openSuccessModal(res.data.msg);
                    that.fetch();
                }).catch(err => {
                    openModalMessage('error', err.message);
                    return;
                })
            }
        })
    }


    handleCancel = e => {
        this.formDrawer && this.formDrawer.resetFields();
        this.setState({
            visible: false,
            drawerVisible: false,
            selectedRowKeys: [],
            selectedRows: [],
        });
        this.fetch();
    };

    handleSearch = value => {
        if (value.createTime) {
            value.createTime = value.createTime.format('YYYY-MM-DD')
        }
        this.setState({ searchItem: value }, this.fetch);
    };

    loadData = (value, dataSource) => {
        console.log(value, dataSource)
        this.newOrCompile(value)
    }
    // 选择某一行数据
    chooseRow = record => {
        let flag = true;
        let index = 0;
        this.state.selectedRowKeys.forEach((row, i) => {
            if (row === record.id) {
                flag = false;
                index = i;
            }
        })
        const selectedRowKeys = this.state.selectedRowKeys;
        const selectedRows = this.state.selectedRows;
        if (flag) {
            selectedRowKeys.push(record.id);
            selectedRows.push(record);
        } else {
            selectedRowKeys.splice(index, 1);
            selectedRows.splice(index, 1);
        }
        this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
    };
    download = () => {
        const { selectedRows } = this.state;
        // if (selectedRows.length) {
        //     this.setState({ downloadLoading: true });
        //     ProductionOrderService.exportProductionOrderParentExcel({ dtoList: selectedRows }).then(res => {
        //         //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
        //         let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
        //         // 创建A标签
        //         let link = document.createElement('a')
        //         link.style.display = 'none'
        //         link.href = url
        //         // 设置的下载文件文件名
        //         const fileName = decodeURI('生产订单管理（父表）');
        //         // 触发点击方法
        //         link.setAttribute('download', fileName)
        //         document.body.appendChild(link)
        //         link.click()
        //         this.setState({ downloadLoading: false })
        //     })
        // } else {
        //     Modal.confirm({
        //         title: '默认导出数据较多，需要较长时间，确认全部导出吗？',
        //         onOk: async () => {
        //             await this.fetchAll();
        //             const { dataSourceAll } = this.state;
        //             await ProductionOrderService.exportProductionOrderParentExcel({ dtoList: dataSourceAll }).then(res => {
        //                 //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
        //                 let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
        //                 // 创建A标签
        //                 let link = document.createElement('a')
        //                 link.style.display = 'none'
        //                 link.href = url
        //                 // 设置的下载文件文件名
        //                 const fileName = decodeURI('生产订单管理（父表）');
        //                 // 触发点击方法
        //                 link.setAttribute('download', fileName)
        //                 document.body.appendChild(link)
        //                 link.click()
        //                 this.setState({ downloadLoading: false })
        //             })
        //         },
        //         onCancel() { }
        //     })
        // }
    }
    fetchAll = async () => {
        const { searchItem, total, formData } = this.state
        searchItem.pageNum = 1
        searchItem.pageSize = total
        searchItem.masterId = formData.id
        await APIService.querySelfCheckDetail(searchItem).then(res => {
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg)
                return
            }
            const dataSourceAll = res.data.data.data
            const selectedRowKeys = dataSourceAll.map(item => item.id);
            this.setState({ dataSourceAll, selectedRowKeys, selectedRows: dataSourceAll })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
    }
    // 打开表单样式预览
    openDetails = () => {
        const { dataSource, formData, searchItem } = this.state
        let data = { title: formData.formName + '-表单样式', searchItem, queryForm: { dataSource, formData, }, path: 'SelfCheckingManage_Detail' }
        localStorage.setItem('SelfChecking_Report', JSON.stringify(data))
        this.props.history.push({ pathname: "/SelfChecking_Report", data })
    }
    resetForm = () => {
        this.formSearch && this.formSearch.resetFields();
        this.setState({
            searchItem: {}
        }, this.fetch);
    }
    render() {
        const { editingKey, loading, dataSource, columns, pageNum, pageSize, total, selectedRowKeys, downloadLoading, searchItem, isAdd, searchItemFather, formData } = this.state;
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys,
                })
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                const keys = [... this.state.selectedRowKeys];
                const rows = [... this.state.selectedRows];
                if (selected) {
                    changeRows.forEach(row => {
                        if (isInvalidObject(keys.find(key => key === row.id))) {
                            keys.push(row.id);
                            rows.push(row);
                        }
                    })
                } else {
                    changeRows.forEach(row => {
                        keys.splice(keys.indexOf(row.id), 1);
                        rows.splice(rows.indexOf(row), 1);
                    })
                }
                this.setState({ selectedRows: rows, selectedRowKeys: keys })
            }
        }
        return (
            <div>
                <BasicLayoutSearch>
                    <PageHeader
                        style={{ padding: '4px 24px' }}
                        onBack={() => this.props.history.push({ pathname: '/SelfCheckingManage', data: { searchItemFather } })}
                        title={<div>{formData?.formCode + ' - ' + formData?.formName + ' - 表单详情'}</div>}
                    >
                    </PageHeader>
                    <Divider />
                    <DetailSearchForm onSearch={this.handleSearch}
                        searchItem={searchItem}
                        resetForm={this.resetForm}
                        ref={node => (this.formSearch = node)}
                    />
                </BasicLayoutSearch>
                <BasicLayout buttons={[
                    <Button key={0} onClick={() => this.openDetails()} type='primary' icon='eye'>表单样式预览</Button>,
                    <Button key={1} type="primary" onClick={() => this.handleAdd()} icon="plus" disabled={isAdd}>新增</Button>,
                    <Button key={2} type="primary" onClick={() => this.handleDelete(1)} icon="delete">删除</Button>,
                    <Button type="primary" key={8} onClick={() => { this.download() }} icon="download" loading={downloadLoading}>导出</Button>,
                ]} name="自检表单维护" icon="table">
                    <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项。说明：为了保证表单样式美观，建议一个表单的检验项不超过25条。</div>} type="info" showIcon style={{ marginBottom: 15 }} />
                    <EditTable
                        dataSource={dataSource}
                        columns={columns}
                        ref={node => (this.editTable1 = node)}
                        rowKey={(record) => record.id}
                        editingKey={editingKey}
                        pagination={false}
                        allowDrafting={true}
                        allowEditable={this.loadData}
                        loading={loading}
                        scroll={{ y: 700, x: 1300 }}
                        rowSelection={rowSelection}
                    // onRow={(record, rowKey) => ({
                    //     onClick: this.chooseRow.bind(this, record, rowKey),
                    // })}
                    />
                    <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
                </BasicLayout>
            </div >
        );
    }
}
export default Form.create()(withRouter(SelfCheckingManageDetail));